import os
from multiprocessing import Process, Queue
import time


def producer(queue):
    for i in range(15):
        queue.put(f"Item {i}")
        print(f"Produced Item {i}")
        time.sleep(1)  # 模拟生产时间


def consumer(queue):
    while True:
        item = queue.get()
        if item is None:  # 使用None作为结束信号
            break
        print(f"Consumed {item}")

import csv


def append_to_csv(file_path, row_data):
    """
    向CSV文件中追加一行数据。

    :param file_path: CSV文件的路径
    :param row_data: 要追加的数据行，作为列表或元组传递
    """
    # 打开CSV文件，使用'a'模式表示追加（append）
    with open(file_path, mode='a', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)

        # 写入一行数据
        writer.writerow(row_data)


if __name__ == "__main__":
    import pandas as pd
    import numpy as np
    from datetime import timedelta

    # 示例数据
    all_data = [
        {"up_time": "2024-12-24 14:34:18.248", "down_time": "2024-12-24 15:34:18.248", "drive_time": 10,
         "plate": "京A100001", "type": "1"},
        {"up_time": "2024-12-24 14:34:24.239", "down_time": "2024-12-24 15:34:24.239", "drive_time": 58,
         "plate": "京A100002", "type": "2"},
        # 添加更多数据...
    ]

    data = all_data.copy()
    # all_data = [item for item in data if item["type"] == "1"]
    all_data = [item for item in data]
    # 将数据转换为DataFrame
    df = pd.DataFrame(all_data)
    # 计算每条记录的速度
    df["speed"] = df["drive_time"].apply(lambda x: 1 / x if x > 0 else 0)
    # 设置下时间戳为索引并确保它是datetime类型
    df.set_index(pd.to_datetime(df["up_time"]), inplace=True)


    # 定义一个自定义函数来计算慢行数量
    def count_slow(speeds, avg_speed):
        threshold = avg_speed * 1.2
        return (speeds < threshold).sum()


    # 按照 type 分组，并在每个时间窗口内计算平均速度和其他统计信息
    result = df.groupby(['type', pd.Grouper(freq="5T")]).agg(
        avg_speed=('speed', 'mean'),
        max_speed=('speed', 'max'),  # 最大速度
        min_speed=('speed', 'min'),  # 最小速度
        count=('speed', 'count'),  # 统计每个窗口内的记录数量
        slow_count=('speed', lambda speeds: count_slow(speeds, speeds.mean()))  # 慢行数量
    ).reset_index()
    # 如果某些时间窗口没有数据，可以通过重采样填充这些窗口

    # 转换为字典（列表记录格式）
    car_mean_speed = result.to_dict(orient='records')
    print(car_mean_speed)

    keys = [d['up_time'] for d in car_mean_speed if d["type"] == "1"]
    print(keys)

    a = []
    for d in car_mean_speed:
        if d["type"] == "1":
            a.append(d["up_time"])
    print(a)

    mean_speeds = [d['avg_speed'] for d in car_mean_speed]
    print(mean_speeds)

    KakoList = [
        {
            'pileNumber': 'ZW3',
            'ip': '10.151.110.120',
            'type': '中维',
            'lon': 106.92890390995352,
            'lat': 30.31307726368321
        },
        {
            'pileNumber': 'ZW4',
            'ip': '10.151.110.124',
            'type': '中维',
            'lon': 106.93466252112233,
            'lat': 30.30702300212657
        }
    ]

    # 转换为字典形式
    KakoDict = {item['pileNumber']: {key: value for key, value in item.items() if key != 'pileNumber'} for item in
                KakoList}

    print(KakoDict)